package com.yzz.shopping.ui.fragment

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.yzz.shopping.R
import com.yzz.shopping.entity.GlideRecommendBean
import com.yzz.shopping.entity.MenuBean
import com.yzz.shopping.entity.ShoppingTypeBean
import com.yzz.shopping.ui.adapter.ShoppingAdapter
import com.yzz.shopping.utils.NetWorkUtils
import com.yzz.shopping.viewmodel.GlideViewModel
import com.yzz.shopping.viewmodel.SearchViewModel
import kotlinx.android.synthetic.main.fragment_shpping_search.*
import kotlinx.android.synthetic.main.item_history.*
import kotlinx.coroutines.launch

/**
 * @Author : yangzuozhe
 * @Time : On 2022/2/24 10:38
 *
 * @Description : ShoppingSearchFragemnt
 */
class ShoppingSearchFragment : Fragment() {
    private var mGlideViewModel: GlideViewModel? = null
    private var mSearchViewModel: SearchViewModel? = null
    private var mMenuBean: MenuBean? = null
    private var mShoppingAdapter: ShoppingAdapter? = null
    private var mSearchContent: String? = ""
    private var mSortName = 0
    private var mIsCoupon = false

    companion object {
        const val MENU_BEAN = "MENU_BEAN"
        private val sShoppingTypeList: MutableList<ShoppingTypeBean?>? by lazy {
            mutableListOf(
                ShoppingTypeBean(
                    GlideViewModel.IStoryType.complex.first,
                    GlideViewModel.IStoryType.complex.second
                ),
                ShoppingTypeBean(
                    GlideViewModel.IStoryType.SalesInDescendingOrder.first,
                    GlideViewModel.IStoryType.SalesInDescendingOrder.second
                ),
                ShoppingTypeBean(
                    GlideViewModel.IStoryType.PriceAscending.first,
                    GlideViewModel.IStoryType.PriceAscending.second,
                    R.mipmap.icon_after_coupon,
                    R.mipmap.icon_un_after_coupon,
                    0
                )
            )
        }

        fun newInstance(menuBean: MenuBean): ShoppingSearchFragment {
            val args = Bundle()
            args.putSerializable(MENU_BEAN, menuBean)
            val fragment = ShoppingSearchFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return LayoutInflater.from(context)
            .inflate(R.layout.fragment_shpping_search, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
        initEmptyView()
        arguments?.let {
            val menuBean: MenuBean? = it.getSerializable(MENU_BEAN) as MenuBean?
            mMenuBean = menuBean
        }

        mShoppingChangeTypeView.addTabViewList(sShoppingTypeList) { str, bo ->
            if (str != null) {
                mSortName = str
            }
            mIsCoupon = bo
            requestData(true)
        }
    }

    private fun initViewModel() {
        mSearchSmartRefresh?.setRefreshHeader(ClassicsHeader(context))
        mSearchSmartRefresh?.setRefreshFooter(ClassicsFooter(context))
        mSearchSmartRefresh?.setOnRefreshListener {
            requestData(true)
            mSearchSmartRefresh?.finishRefresh()
        }
        mSearchSmartRefresh?.setOnLoadMoreListener {
            requestData(false)
            mSearchSmartRefresh?.finishLoadMore()
        }
        mIvDeleteHistory?.setOnClickListener {
            mSearchViewModel?.clearHistoryInfo()
        }
        mGlideViewModel = ViewModelProvider(this).get(GlideViewModel::class.java)
        mGlideViewModel?.searchBeanLiveData?.observe(viewLifecycleOwner) {
            if (it != null) {
                initData(it)
            } else {

            }
        }
        activity?.let { ac ->
            mSearchViewModel = ViewModelProvider(ac).get(SearchViewModel::class.java)
            lifecycleScope.launch {
                    mSearchViewModel?.mSearchContentLiveData?.observe(viewLifecycleOwner) {
                        lifecycleScope.launchWhenResumed {
                            if (it != null) {
                                mSearchViewModel?.mIsHistoryVisibility?.value = false
                                if (SearchViewModel.SEARCH_CONTENT == it) {
                                    mSearchContent = it
                                    requestData(true)
                                }

                            }
                        }
                    }
            }

            mSearchViewModel?.searchListLiveData?.observe(ac) {
                initSearchHistory(it)
            }
            mSearchViewModel?.mIsHistoryVisibility?.observe(ac) {
                if (it) {
                    mIncludeHistoryView?.visibility = View.VISIBLE
                } else {
                    mIncludeHistoryView?.visibility = View.GONE
                }
            }
            mSearchViewModel?.getSearchHistoryList()
        }
    }

    private fun initEmptyView() {
        mShoppingSearchEmptyView?.setRetryCLick {
            mShoppingSearchEmptyView?.setEmptyIsShow(false)
            if (mShoppingAdapter == null) {
                requestData(true)
            } else {
                requestData(false)
            }
        }
    }


    private fun requestData(isFirst: Boolean) {
        mMenuBean?.let { bean ->
            mGlideViewModel?.requestSearch(
                bean.type.toInt(),
                mSearchContent,
                mIsCoupon,
                mSortName,
                isFirst
            )
        }
    }

    private fun initData(pair: Pair<Int, ArrayList<GlideRecommendBean?>?>?) {
        val page = pair?.first
        val list = pair?.second
        mShoppingSearchEmptyView?.setEmptyIsShow(false)
        if (mShoppingAdapter == null) {
            if (list != null && list.isNotEmpty()) {
                val ac = activity
                if (ac != null) {
                    mShoppingAdapter = ShoppingAdapter(ac, list, true)
                    mRvmSearchShopping.adapter = mShoppingAdapter
                    mRvmSearchShopping.layoutManager = LinearLayoutManager(context)
//                    BackToTopUtils.instance.initBackToTop(
//                        ShoppingFragment.IS_SEARCH_NESTED,
//                        mRvmSearchShopping,
//                        mIvSearchBackToTop
//                    )
                }
            } else {
                setErrorEmptyShow()
            }
        } else {
            if (list != null && list.isNotEmpty()) {
                if (page == 1) {
                    mShoppingAdapter?.refreshData(list)
                    if (mShoppingAdapter?.itemCount ?: 0 > 0) {
                        mRvmSearchShopping?.scrollToPosition(0)
                    }
                } else {
                    mShoppingAdapter?.loadMore(list)
                }
            } else {
                if (page == 1) {
                    setErrorEmptyShow()
                }
            }
        }
    }

    private fun setErrorEmptyShow() {
        val con = context
        if (con != null) {
            if (NetWorkUtils.hasInternet()) {
                mShoppingSearchEmptyView?.setEmptyMessage()
            } else {
                mShoppingSearchEmptyView?.setErrorMessage()
            }
        } else {
            mShoppingSearchEmptyView?.setErrorMessage()
        }
    }


    private fun initSearchHistory(list: MutableList<String?>?) {
        if (list != null && list.isNotEmpty()) {
            mSearchFlexLayout?.removeAllViews()
            list.forEach { str ->
                val view = layoutInflater.inflate(R.layout.item_search_icon, null)
                val textView = view.findViewById<TextView>(R.id.mTvSearchItem)

                textView?.text = str
                textView?.setOnClickListener {
                    str?.let { it1 ->
                        mSearchViewModel?.searchContent(it1)
                        hideSoftInput(mSearchFlexLayout)
                    }
                }
                mSearchFlexLayout?.addView(view)
            }
        } else {
            mSearchFlexLayout?.removeAllViews()
        }
    }

    private fun hideSoftInput(view: View?) {
        if (view != null) {
            val activity = view.context as Activity?
            val imm =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            //ps：这是强制隐藏键盘的代码，因此如果想要显示键盘用上面那句话，隐藏键盘用下面这句话
            imm?.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

}